package com.yzw.common.handler;

import com.yzw.common.dto.R;
import com.yzw.common.exception.CustomException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@ControllerAdvice
public class GlobalExceptionHandler {

    //指定出现什么异常执行这个方法
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody //为了返回数据
    public R error(RuntimeException e) {
        e.printStackTrace();
        return R.error("系统异常");
    }

    /**
     * 自定义异常
     */
    @ExceptionHandler(CustomException.class)
    @ResponseBody //为了返回数据
    public R error(CustomException e) {
        e.printStackTrace();
        return R.error(e.getCode(),e.getMsg());
    }
    //后端数据校验的异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody //为了返回数据
    public R error(MethodArgumentNotValidException e) {
        StringBuffer errorMsg = new StringBuffer();
        BindingResult bindingResult = e.getBindingResult();
        if(bindingResult.hasErrors()){
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for(FieldError fieldError : fieldErrors){
                errorMsg.append(fieldError.getDefaultMessage()+",");
            }
        }
        //去掉最后一个逗号
        String substring = errorMsg.substring(0, errorMsg.lastIndexOf(","));
        return R.error("系统异常:"+substring);
    }
}